﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using MyBlog.IRepository;
using MyBlog.Model;
using SqlSugar;
using SqlSugar.IOC;

namespace MyBlog.Repository
{
    /*
     仓储模式 实现类
     */
    public class BaseRepository<TEntity> : SimpleClient<TEntity> , IBaseRepository<TEntity> where TEntity : class, new()
    {
        public BaseRepository(ISqlSugarClient context = null):base(context)//构造函数
        {
            base.Context = DbScoped.Sugar;
            //// 创建数据库
            //base.Context.DbMaintenance.CreateDatabase();
            //// 创建表
            //base.Context.CodeFirst.InitTables(
            //  typeof(BlogNews),
            //  typeof(TypeInfo),
            //  typeof(WriterInfo)
            //);
        }

        public async Task<bool> CreateAsync(TEntity entity)//增加
        {
            return await base.InsertAsync(entity);
        }

        public async Task<bool> DeleteAsync(int id)//删除
        {
            return await base.DeleteByIdAsync(id);
        }

        public async Task<bool> EditAsync(TEntity entity)//修改
        {
            return await base.UpdateAsync(entity);
        }

        //虚方法
        public virtual async Task<TEntity> FindAsync(int id)//查询
        {
            return await base.GetByIdAsync(id);
        }
        //虚方法
        public virtual async Task<TEntity> FindAsync(Expression<Func<TEntity, bool>> func)
        {
            return await base.GetSingleAsync(func);
        }
        //虚方法
        public virtual async Task<List<TEntity>> QueryAsync()//查询全部数据
        {
            return await base.GetListAsync();
        }
        //虚方法
        public virtual async Task<List<TEntity>> QueryAsync(Expression<Func<TEntity, bool>> func)//自定义条件查询
        {
            return await base.GetListAsync(func);
        }
        //虚方法
        public virtual async Task<List<TEntity>> QueryAsync(int page, int size, RefAsync<int> total)//分页查询
        {
            return await base.Context.Queryable<TEntity>()
                .ToPageListAsync(page, size, total);
        }

        //虚方法
        //自定义条件分页查询
        public virtual async Task<List<TEntity>> QueryAsync(Expression<Func<TEntity, bool>> func, int page, int size, RefAsync<int> total)
        {
            return await base.Context.Queryable<TEntity>()
                .Where(func)
                .ToPageListAsync(page, size, total);
        }
    }
}
